package com.lyl.cloud.controller;

import cn.hutool.core.date.DateUtil;
import com.lyl.cloud.common.base.Result;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestOperations;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class TestController {

    public static final String PAYMENT_SERVICE = "http://CLOUD-PROVIDER-PAYMENT-SERVICE";
    @Resource
    private RestOperations restOperations;
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/hello")
    public String hello(){
        String str = "hello,world i come from china";
        System.out.println("str = " + str);
        return str;
    }

    @GetMapping("/hello2")
    public Result hello2(){
        String str = "hello,world i come from chinese , return a Result class instance";
        System.out.println("str = " + str);
        return Result.success(str);
    }

    @GetMapping("/test2")
    public Result test2(){
        ResponseEntity<Result> response = restOperations.getForEntity(PAYMENT_SERVICE + "/test2", Result.class);
        System.out.println("请求状态码 = " + response.getStatusCodeValue());
        if (response.getStatusCodeValue() == 200){
            System.out.println("请求成功 : " + DateUtil.now());
            return response.getBody();
        }
        System.out.println( "请求失败 : " + DateUtil.now());
        return Result.fail();
    }

    @GetMapping("/discover")
    public Result discover(){
        List<ServiceInstance> instanceList = discoveryClient.getInstances("CLOUD-PROVIDER-PAYMENT-SERVICE");
        for (ServiceInstance instance : instanceList) {
            System.out.println(instance.getInstanceId() + "\t" + instance.getUri() + "\t" + instance.getHost() + "\t" + instance.getPort()
                    + "\t" + instance.getServiceId());
        }
        return Result.success(instanceList);
    }

}
